
package cz.czu.pef.DataModelling.utils;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;


@Configurable
@Component
@Aspect
public class StopWatchAspect
{

	private static final Logger logger = Logger.getLogger(StopWatchAspect.class.getName());

	@Pointcut("execution(* cz.czu.pef.DataModelling.dao.impl.*.*(..))")
	public void daoImplMethods() { }

	@Around("daoImplMethods()")
	public Object profileDaoImpl(ProceedingJoinPoint pjp) throws Throwable
	{
		return profile(pjp);
	}


	@Pointcut("execution(* cz.czu.pef.DataModelling.ejb.impl.*.*(..))")
	public void ejbImplMethods() { }

	@Around("ejbImplMethods()")
	public Object profileEjbImpl(ProceedingJoinPoint pjp) throws Throwable
	{
		return profile(pjp);
	}
	
	
	@SuppressWarnings("rawtypes")
	private Object profile(ProceedingJoinPoint pjp) throws Throwable
	{
		try
		{
			long start = System.currentTimeMillis();

			//System.out.println("Going to call the method.");
			Object output = pjp.proceed();
			//System.out.println("Method execution completed.");
			long elapsedTime = System.currentTimeMillis() - start;

			if (logger.isLoggable(Level.FINE))
			{
				Class clazz = pjp.getTarget().getClass();
				String name = pjp.getSignature().getName();
				logger.fine(clazz + "." + name + "():: Took " + elapsedTime + " ms");
			}

			return output;
		}
		catch (Throwable th)
		{
			logger.severe("profile():: Unhandled exception caught: " + th.getStackTrace());
			throw th;
		}
		finally
		{
		}
	}

}